# -*- coding: utf-8 -*-

import appuifw, e32
from appuifw import *
from key_codes import EKeyRightArrow, EKeyLeftArrow
import json, time, urllib, re

class Screen:
    def __exit__(self):
        self.lock.signal()

    def cal(self):
        pass

    def next(self):
        p=self.p
        self.items[p+1]=self.items[p+2]
        self.items[p+2]=self.items[p+3]
        x=self.items[p+3].split(":")[0]
        x=(int(x)+1)%24
        self.items[p+3]=self.hour(x)
        self.nastepny()
        self.list.set_list(self.items)

    def prev(self):
        p=self.p
        self.items[p+3]=self.items[p+2]
        self.items[p+2]=self.items[p+1]
        x=self.items[p+1].split(":")[0]
        x=(int(x)-1)%24
        self.items[p+1]=self.hour(x)
        self.nastepny()
        self.list.set_list(self.items)

    def __init__(self):
        self.p = 2
        self.items=[u'' for xs in range(self.p+1)]
        appuifw.app.exit_key_handler = self.__exit__
        appuifw.app.screen = "large"#"full"
        self.lock=e32.Ao_lock()
        app.body = self.list = Listbox(self.items, self.cal)

        self.main()
        self.nastepny()

        self.list.bind(EKeyRightArrow, self.next)
        self.list.bind(EKeyLeftArrow, self.prev)
        self.list.set_list(self.items)
        self.lock.wait()

    def dq(self, x):
        try:
            s=u"http://autobuser.pl/autobuser_api.php?q=%s:%s"%x
        except:
            s=u"http://autobuser.pl/autobuser_api.php?q=%s"%(x)
        u = urllib.urlopen(s)
        s = u.read()
        u.close()
        s=re.sub('\\\\u.{4}','x',s)
        return unicode(s)

    def hour(self, h):
        hs=unicode(str(h))
        try:
            oh=self.rozk[hs]
        except:
            return hs
        minutes=oh.keys()
        minutes.sort()
        out=[]
        for m in minutes:
            try:
                for a,b in oh[m].items():
                    m=m+str(b)
            except:
                pass
            out.append(m)

        return unicode(hs+u":"+u" ".join(out))

    def nastepny(self):
        t=time.time()-time.altzone
        h=int(t%(60*60*24))/60/60
        ho=h
        mi=int(t%(60*60*24))/60%60
        li=0
        za=[]
        while len(za)<5:
            hs=unicode(str(h))
            try:
                minutes=self.rozk[hs].keys()
            except:
                return hs

            minutes.sort()
            out=[]
            ti=h-ho
            ti*=60
            for m in minutes:
                tx=ti+int(m)-mi
                if tx>0:
                    za.append(str(tx))
            h+=1

        self.items[self.p]=unicode(u'za:'+u' '.join(za))

    def main(self):
        line = appuifw.query(u"Linia nr:", u'text')
        x=self.dq(line)
        x = json.read(x)
        linie=x[u'linie']
        L=[]
        for l,w in linie.items():
            for a,b in w.items():
                L.append(l+u":"+a)
        test = appuifw.selection_list(L)
        [l,k]=L[test].split(u":")
        tr=linie[l][k]
        naz=map(unicode,tr[0][u'trasa'][u'nazwa'])
        test = appuifw.selection_list(naz)
        st = tr[0][u'trasa'][u'id_przystanku'][test]
        x=json.read(self.dq((line,st)))
        rozklad=x[u'rozklady']
        rozklad=rozklad[u'%s:%s'%(line,st)]
        test=appuifw.popup_menu([u"Dzien powszedni",u"Swieto/sobota"], u"Wybierz dzien:")
        ps=[u'p',u's'][test]
        self.rozk=rozklad[ps]
        #rozklad[u'zmiany']
        self.items[0]=unicode(rozklad[u'linia']+u'->'+rozklad[u'kierunek'])
        self.items[1]=unicode(rozklad[u'nazwa'])

        t=time.time()-time.altzone
        ho=int(t%(60*60*24))/60/60

        for h in [ho,ho+1,ho+2]:
            xh=self.hour(h)
            self.items.append(xh)

if __name__ == u"__main__":
    Screen()
